// 1. 渲染页面 :
var data_g = null;

function render() {
    $.ajax("/pxx", {
            data: {
                pdduid: 0,
                page: 1,
                size: 30,
                list_id: "promotion_subject21933_8tdjNJ_spike_1_0",
                day_type: 1,
                tab: 0,
                component_mark: "20190822_sub_21933_秒杀商品-赛马专属-周促",
                anti_content: "0anAfanUdilYq9dVyruXwHj_G2ZC_tg1CJXZv86_pXSTHnS-tG_XUX5-FFsiAXjkwXMpvfnzLC2JC1mkVEHlT9Hc9sz1v9OzeRNRGjWNlTz9t9hr9fOPodA8ZUoMYMiU2__QxdR_R3zRtD9SrA_8ig2c-Ydk6jviqUSm6Y64SK0iPXzYyNfYbpy1kLMweV-7nHgEIDCrkITSZG7x3IPZxEOVsiho5-QBZyKrcxy7rkaQ3YuYO3u-HZeLOkRka8iWaBwrbey8aVMLzepm1WD8HWJkAaYZdyKcifp7hFFXlXiqRaklGeOXRloGPtml3-PiW1otCXPaI5IgjkesshEf4eFR12RmY7PKrsP6XSxuZm08gueSS0_di9PJ4Ftiwn4BGdnxI02DBKCridiYG9PKV_ld2tZsH9qFBm1HxYKaeZsKHM4YfT5mjKgFUUJ5kGAsl3Veupk_Bo0Z_lY7Zf9dtBBZjBapDXHYf-BymbgqFQmycIPvTMzr4Oyr-sZBHW1zvF-WXG0TuIS5sSknu7lSlrl8biSzDIC3ZzQsHzaAKLPWiB3yulow-yHk9p8y6go0kKY8oEMksn8h0Gc4AEvE-MWAgO8LOUiSjPLhSqG5jbnwcHCh54I3Ypk1iDTMShxthTtQjW5S2NuJ6WMIONyiReJbW6V7iwNOJJ"
            }
        })
        .then(function (res) {
            var list = res.items;
            data_g = list;
            var html = "";
            for (var i = 0; i < list.length; i++) {
                html += `<div class="col-md-3 goods-item" data-id="${list[i].data.id}" data-index=${ i }>
                                    <img class="img-thumbnail" src="${list[i].data.hd_thumb_url}" alt="">
                                    <p title="${list[i].data.goods_name}">${list[i].data.goods_name}</p>
                                    <h2>${(list[i].data.normal_price / 100) .toFixed(2)}</h2>
                                    <button class="btn btn-danger add-cart">加入购物车</button>
                              </div>`;
            }
            $(".goods-list").html(html);
        });
}
render();

// 购物车共有三个功能 : 购物车就是一个数组 : 增 删 该 查;

// 先去获取一下localStorage ;
var cart_list = (function () {
    var storage = localStorage.getItem("carts");
    if (storage === null) {
        return [];
    }
    return JSON.parse(storage);
})();

//购物车在加购时触发 add 的里面的函数;
var add_callback = $.Callbacks();

// 更改购物车的数量;
add_callback.add(sumGoodsCount);

function sumGoodsCount() {
    var total = cart_list.reduce(function (prev, item) {
        var prev_num = typeof prev === "number" ? prev : prev.count;
        return prev_num + item.count;
    })
    $(".cart-count").html(total);
}

sumGoodsCount();
// 购物车的增加功能 ;
$(".goods-list").on("click", ".add-cart", function () {
    // 向数组之中添加数据 => 咋添加数据那 ? 添加啥那 ? 
    // 找到这个元素的索引 : 
    var index = $(this).parent().attr("data-index");
    var item = data_g[index];
    // 找到具体的数据之后放入数组之中;
    // cart_list.push(item);
    // 此时的添加分成两种情况 :
    // 1. 当前的数组里没有这个商品! 直接完整的添加;
    // 2. 当前数组里有这个商品 ! count 自增即可;
    // 判定当前购物车列表是否存在这个商品!;
    var has_same = cart_list.some(function (cart_item) {
        // cart_item 购物车里面的每一个商品;
        if (item.data.goods_id == cart_item.data.goods_id) {
            cart_item.count++;
            return true; // 存在相同的商品;
        }
    });

    if (!has_same) {
        // 添加一个新的商品进数组;
        item.count = 1;
        cart_list.push(item);
    }

    // 做个其他的事;
    // 每次操作完数据都保存一下;
    localStorage.setItem("carts", JSON.stringify(cart_list));
    add_callback.fire();
})